package teacher;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;
import java.util.*;

/*
 * 5. 每个电影前三名的评分
 */
public class Score5 {

    public static class Score5Mapper extends Mapper<LongWritable, Text, Text, IntWritable> {

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString();
            String[] split = line.split("::");
            // 假设输入数据的格式是：电影ID::电影名::评分::其他信息1::其他信息2，我们取电影ID作为key，评分作为value
            context.write(new Text(split[4]), new IntWritable(Integer.parseInt(split[2])));
        }
    }

    public static class Score5Reducer extends Reducer<Text, IntWritable, Text, IntWritable> {

        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            List<Integer> list = new ArrayList<>();
            for (IntWritable value : values) {
                list.add(value.get());
            }
            Collections.sort(list, Collections.reverseOrder()); // 降序排序

            // 取出前三名评分
            for (int i = 0; i < Math.min(3, list.size()); i++) {
                context.write(key, new IntWritable(list.get(i)));
            }
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        Configuration config = new Configuration();
        Job job = Job.getInstance(config);
        job.setJarByClass(Score5.class);
        job.setMapperClass(Score5Mapper.class);
        job.setReducerClass(Score5Reducer.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        FileSystem fs = FileSystem.get(config);
        // 读取电影和评分后的关联数据
        Path inputPath = new Path(Config.TEMP_PATH+"\\part-m-00000");
        Path outputPath = new Path(Config.OUT_PATH[5]);
        if (fs.exists(outputPath)) {
            fs.delete(outputPath, true);
        }
        FileInputFormat.setInputPaths(job, inputPath);
        FileOutputFormat.setOutputPath(job, outputPath);

        boolean isDone = job.waitForCompletion(true);
        System.out.println(isDone ? "执行成功" : "执行失败");
    }
}